package service

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/sdk/service"
	"gorm.io/gorm"

	"ssdevice/common/constant"
	cDto "ssdevice/common/dto"
	"ssdevice/common/enums"
	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/command"
	"ssdevice/internal/device/models/query"
)

type Gateway struct {
	sysDevModel    *models.SysDev
	devSchemaModel *models.SysDevSchema
	devConfigModel *models.SysDevConfig
	devSensorModel *models.SysDevSensor
	devSystemModel *models.SysDevSystem
	service.Service
}

func (d *Gateway) SetDevModel(m *models.SysDev) *Gateway {
	d.sysDevModel = m
	return d
}

func (d *Gateway) SetSchemaModel(m *models.SysDevSchema) *Gateway {
	d.devSchemaModel = m
	return d
}

func (d *Gateway) SetConfigModel(m *models.SysDevConfig) *Gateway {
	d.devConfigModel = m
	return d
}

func (d *Gateway) SetSensorModel(m *models.SysDevSensor) *Gateway {
	d.devSensorModel = m
	return d
}

func (d *Gateway) SetSystemModel(m *models.SysDevSystem) *Gateway {
	d.devSystemModel = m
	return d
}

func (d *Gateway) ModSoftGateway(req *command.DeviceEditReq) (err error) {
	if err = d.sysDevModel.FindOne(d.sysDevModel, cDto.MakeCondition(query.SysDevQuery{IdSn: req.Id, TypeNot: enums.DevTypeOfDevice})); err != nil {
		return
	}
	if err = d.Orm.Transaction(func(tx *gorm.DB) error {
		d.sysDevModel.Orm = tx
		// 可编辑项
		if len(req.Name) > 0 {
			d.sysDevModel.Name = req.Name
		}
		if len(req.DeptId) > 0 {
			d.sysDevModel.DeptId = req.DeptId
		}
		//if len(req.ProductModel) > 0 {
		//	d.sysDevModel.ProductModel = req.ProductModel
		//}
		if len(req.Location) > 0 {
			d.sysDevModel.Location = utils.MapToBytes(req.Location)
		}
		// 编辑dev
		if err = d.sysDevModel.Mod(d.sysDevModel); err != nil {
			return err
		}
		// 调用服务
		if err = ctrlSoftGatewayServe(d.sysDevModel, enums.Modify); err != nil {
			return err
		}

		err = env.Cache.HashSet(constant.DeviceDeptCache, map[string]interface{}{d.sysDevModel.Sn: d.sysDevModel.DeptId})
		return nil
	}); err != nil {
		return
	}
	return
}
